<style lang="less">
@import "developList.less";
</style>
<template>
  <div class="search">
    <div>
      <Card>
        <Row style="margin-top: 1%;border: 1px solid #dcdee2; border-color: #e8eaec; ">
          <Form ref="searchForm" :model="searchForm" inline :label-width="160" class="search-form"
            style="margin-top: 10px">
            <Row class="operation">
              <i-col span="8">
                <Form-item label="合作商名称" prop="channelFullName">
                  <Input type="text" v-model="searchForm.channelFullName" clearable placeholder="请输入合作商名称"
                    style="width: 200px" />
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="上线起止日期" prop="onlineDate">
                  <DatePicker v-model="selectDate" type="daterange" format="yyyy-MM-dd" @on-change="selectDateRange"
                    placeholder="选择起止时间" style="width: 200px">
                  </DatePicker>
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="状态" prop="channelStatus">
                  <Select v-model="searchForm.channelStatus" placeholder="请选择" clearable style="width: 200px">
                    <Option :value="item.value" v-for="(item,index) in channelStatusList" :key="index">
                      {{item.title}}</Option>
                  </Select>
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="法人" prop="legalPerson">
                  <Input type="text" v-model="searchForm.legalPerson" clearable placeholder="请输入法人名称"
                    style="width: 200px" />
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="优质等级" prop="qualityGrade">
                  <Select v-model="searchForm.qualityGrade" placeholder="请选择" clearable style="width: 200px">
                    <Option :value="item.value" v-for="(item,index) in qualityGradeList" :key="index">
                      {{item.title}}</Option>
                  </Select>
                </Form-item>
              </i-col>
              <i-col span="8">
                <!-- <FormItem label="注册省市" prop="channelAddress" >
                    <Cascader :data="location" v-model="searchForm.addressinfo" style="width:200px;" :load-data="loadData"></Cascader>
                </FormItem> -->
                <FormItem label="注册省市" prop="channelAddress" >
                    <Cascader :data="location" v-model="searchForm.addressinfo" @on-change="handleChannelAddress" change-on-select filterable style="width:200px;" :load-data="loadData"></Cascader>
                </FormItem>
              </i-col>

              <i-col span="8">
                <Form-item label="渠道归属" prop="channelBelong">
                  <Select v-model="searchForm.channelBelong" placeholder="请选择" clearable style="width: 200px">
                    <Option :value="item.value" v-for="(item,index) in channelBelongList" :key="index">
                      {{item.title}}</Option>
                  </Select>
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="合作商评级" prop="channelGrade">
                  <Select v-model="searchForm.channelGrade" placeholder="请选择" clearable style="width: 200px">
                    <Option value="1">A</Option>
                    <Option value="2">B</Option>
                    <Option value="3">C</Option>
                    <Option value="4">D</Option>
                  </Select>
                </Form-item>
              </i-col>
              <i-col span="8">
                <Form-item label="业务类型" prop="businessAttributes">
                  <Checkbox v-bind:disabled="typeHide" v-model="searchForm.newCar">新车</Checkbox>
                  <Checkbox v-bind:disabled="typeHide" v-model="searchForm.oldCar">二手车</Checkbox>
                </Form-item>
              </i-col>

              <i-col span="8">
                <Form-item label="区域经理" prop="userName">
                  <Select v-model="searchForm.userName" filterable clearable   style="width: 200px">
                  <Option :value="item.userName+''" v-for="(item,index) in customerManagerList" :key="index">{{item.userRealName}}
                  </Option>
                  <!-- <Option v-for="item in baseInfo" :value="item.id" :key="item.id">{{ item.channelFullName }}</Option> -->
                </Select>
                </Form-item>
              </i-col>
              <!-- </span> -->
              
            </Row>
            <Row style="text-align: center">
              <Form-item style="margin-left:-60px; text-align: center" class="br">
                <Button @click="handleSearch" type="primary" icon="ios-search">查询</Button>
                <Button @click="handleReset" icon="md-redo">重置</Button>
              </Form-item>
            </Row>
          </Form>
        </Row>
        <Row class="code-row-bg" justify="start" type="flex" style="margin-top: 20px;">
          <i-col span="6" style="border: 1px solid #dcdee2; border-color: #e8eaec;">
            <!-- <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="输入区域名搜索" /> -->
            <div class="tree-bar">
              <Tree ref="tree" :data="areaData" :load-data="areaLoadData" @on-check-change="changeSelect"
                @on-select-change="selectTree"></Tree>
            </div>
            <Spin fix size="large" v-if="loading"></Spin>
          </i-col>
          <i-col span="17" style="margin-left: 50px">
            <Row class="operation">
              <Button v-if="businessTypeChannel!=null||ownBusinessTypeChannel!=null" @click="upBatch" type="primary" icon="md-add">批量修改区域经理</Button>
            </Row>
            <Row>
              <Table :loading="loading" border :columns="columns" :data="data" sortable="custom"
                @on-sort-change="changeSort" @on-selection-change="showSelect" ref="table">
                <template slot-scope="{ row }" slot="channelFullName">
                  <a type="primary" size="small" @click="showChannelName(row)">{{row.channelFullName}}
                  </a>
                </template>

                <template slot-scope="{ row }" slot="channelStatus">
                  <span>{{setChannelStatusTitle(row.channelStatus)}}</span>
                </template>
                <template slot-scope="{ row }" slot="channelGrade">
                  <span>{{setChannelGradeTitle(row.channelGrade)}}</span>
                </template>
                <template slot-scope="{ row }" slot="businessType">
                  <span>{{setBusinessTypeTitle(row.businessType)}}</span>
                </template>
                <template slot-scope="{ row }" slot="customerManager">
                  <span>{{setCustomerManagerTitle(row.customerManager)}}</span>
                </template>
                <template slot-scope="{ row }" slot="qualityGrade">
                  <span>{{setQualityGradeTitle(row.qualityGrade)}}</span>
                </template>
                <template slot-scope="{ row }" slot="channelStatusOldCar">
                  <span>{{setChannelStatusOldCarTitle(row.channelStatusOldCar)}}</span>
                </template>
                <template slot-scope="{ row }" slot="channelBelong">
                  <span>{{setChannelBelongTitle(row.channelBelong)}}</span>
                </template>


                <!--翻译省市-->
                <template slot-scope="{ row, index }" slot="address">
                  <span>{{getDetailAddress(row.channelProvince,row.channelCity,row.channelAddress)}}</span>
                </template>
              </Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small"
                show-total show-elevator show-sizer></Page>
            </Row>
            <Modal v-model="modal2" width="360">
        <p slot="header" style="color:#f60;text-align:center">
          <Icon type="ios-information-circle"></Icon>
          <span>已选择：{{this.clickCount}} 条数据</span>
        </p>
        <div style="text-align: center;">
          <Select v-model="areaManager" placeholder="区域经理"  class="w200">
            <Option v-for="(item,index) in userAreaManger" :value="item.userName" :label="item.userRealName"
              :key="index">
            </Option>
          </Select>
          <div style="padding-top: 10px;">
          <RadioGroup v-model="border" @on-change="checkArea" >
            <Radio v-bind:disabled="clickHide" label="0" border>新车</Radio>
            <Radio v-bind:disabled="clickHide" label="1" border>二手车</Radio>
          </RadioGroup>
          </div>
        </div>
        <div slot="footer">
          <Button type="error" size="large" long @click="dels">确认</Button>
        </div>
      </Modal>
          </i-col>
        </Row>
      </Card>
    </div>
  </div>
</template>

<script>
import {
  getByDevelop,
  deleteChannel,
  batchManager
} from "@/projects/afs-channel/api/dealer/dealer";
import {
  getAllAddressList,
  getRoleType,
  getAllRegionalManager
} from "_p/afs-channel/api/common/common.js";

import { getDictDataByType } from "_p/basic/api/admin/datadic";
import { savechannelDevelopment } from "@/projects/afs-channel/api/develop/develop";
import { deepClone } from "../../../../../libs/utils/ObjectClone";
import {
  initDepartment,
  loadDepartment,
  addDepartment,
  editDepartment,
  deleteDepartment,
  searchDepartment
} from "@/projects/basic/api/admin/department";
import {
  getLocation,
  initAppertainRegion,
  addAppertainRegion,
  editAppertainRegion,
  deleteAppertainRegion,
  searchAppertainRegion,
  getUserByParentId
} from "_p/afs-channel/api/admin/appertainRegion";
import {
        getAllRoleList,
    } from "@/projects/basic/api/admin/role";
import {
        getAllUserData,
    } from "@/projects/basic/api/admin/user";
export default {
  name: "channelManage",
  components: {},
  data() {
    return {
      userList:[],// 所有的用户集合
      //省市
      province:[],
      city:[],
      location: [],

       // 下面2个是用于控制权限的
      businessTypeChannel:null,
      ownBusinessTypeChannel:null,


      businessAttributes: "", // 业务类型
      typeHide: null, // 控制新车二手车隐藏的功能
      clickList: [], //选中的数据集合
      clickCount: 0, //选中的数量
      clickHide: null, // 控制批量更换区域经理人的隐藏功能
      searchKey: "", // 地域树搜索框

      // 下面是部门树所用的东西
      areaData: [],
      // 弹窗使用
      modal2: false,
      border: "0",
      regionalManager: [],
      regionalManagerOld: [],
      userAreaManger: [],
      areaManager: "", // 修改的区域经理

      parentGroup: true, //父页面默认展示
      loading: true,
      operationLoading: false,
      loadingExport: true,
      drop: false,
      dropDownContent: "更多",
      dropDownIcon: "ios-arrow-down",
      selectCount: 0,
      selectList: [],
      selectAuthFegion: [],
      authFegionDate: [],
      userModalVisible: false,
      expandLevel: 0,
      //当前用户是否拥有新车权限：默认否
      isNewCarRole: "0",
      //当前用户是否拥有二手车权限：默认否
      isOldCarRole: "0",
      //新车合作商状态字典处理
      channelStatusList: [],
      //二手车合作商账号字典处理
      channelStatusOldCarList: [],
      //合作商评级字典处理
      channelGradeList: [],
      //业务类型字典处理
      businessTypeList: [],
      //客户经理字典处理
      customerManagerList: [],
      //优质等级字典处理
      qualityGradeList: [],
      //渠道归属
      channelBelongList: [],
      authFegion: [],
      searchForm: {
        pageNumber: 1,
        pageSize: 10,
        channelFullName: "",
        channelStatus: "",
        legalPerson: "",
        authFegion: "",
        channelAddress: "",
        channelBelong: "",
        channelGrade: "",
        qualityGrade: "",
        startDate: "",
        endDate: "",
        channelStatusOldCar: "",
        userName:"",// 用户名

        addressinfo: [],
        channelCity:"",
        newCar: false, // 选中新车
        oldCar: false, // 选择二手车

        // 下面几个条件是点击左边区域树出来的
        regionLevel: null, // 层级
        regionId: null, // 选中的id
        userId:null, // 用户id
        lowerUserIds:[], //子类id
      },
      selectDate: null,
      modalType: 0,
      channelModalVisible: false,
      modalTitle: "",
      channelForm: {
        sex: 1,
        type: 0,
        channelType: ""
      },
      channelFormValidate: {
        channelType: [
          { required: true, message: "渠道上线类型不能为空", trigger: "blur" }
        ]
      },
      columns: [
        {
          type: "selection",
          minWidth: 60,
          maxWidth: 60,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          title: "序号",
          minWidth: 80,
          align: "center",
          fixed: "left"
        },
        {
          title: "合作商名称",
          key: "channelFullName",
          minWidth: 120,
          align: "center",
          fixed: "left",
          slot: "channelFullName"
        },
        {
          title: "法人",
          key: "legalPerson",
          align: "center",
          minWidth: 145
        },
        {
          title: "上线日期",
          key: "onlineDate",
          align: "center",
          minWidth: 150
        },
        {
          title: "注册地",
          slot: "address",
          align: "center",
          minWidth: 150
        },
        {
          title: "渠道归属",
          key: "channelBelong",
          align: "center",
          minWidth: 115,
          slot: "channelBelong"
        },
        {
          title: "主营品牌",
          key: "mainBrand",
          minWidth: 180,
          ellipsis: true,
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {
                    display: "inline-block",
                    width: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap"
                  },
                  domProps: {
                    title: params.row.mainBrand
                  }
                },
                params.row.mainBrand
              )
            ]);
          }
        },

        {
          title: "业务属性",
          key: "businessType",
          align: "center",
          minWidth: 150,
          slot: "businessType"
        },
        {
          title: "客户经理",
          key: "customerManager",
          align: "center",
          minWidth: 150,
          slot: "customerManager"
        },
        {
          title: "合作商评级",
          key: "channelGrade",
          align: "center",
          minWidth: 150,
          slot: "channelGrade"
        },
        {
          title: "优质等级",
          key: "qualityGrade",
          align: "center",
          minWidth: 150,
          slot: "qualityGrade"
        },
        {
          title: "新车合作商状态",
          key: "channelStatus",
          align: "center",
          minWidth: 140,
          slot: "channelStatus"
        },
        {
          title: "二手车合作商状态",
          key: "channelStatusOldCar",
          align: "center",
          minWidth: 140,
          slot: "channelStatusOldCar"
        },
        {
          title: "下一处理人",
          key: "next_owner",
          align: "center",
          minWidth: 150
        }
      ],
      data: [],
      total: 0
    };
  },
  methods: {
    init() {
      //翻译省市
      this.getProvinceData();
      this.getCityData();
      this.getLocationData();


      this.getMainAreaList();
      this.initLabelType();
      this.getAllRegionalManager();

      // 获取部门树
      this.getParentList();
      // 获取权限顺便查询合作商信息
      this.getRole();
      // 获取数据
      this.getChannelList();
      // this.getAllUser();
    },
    // 查询所有的用户
    getAllUser() {
                getAllUserData().then(res => {
                    if (res.code === "0000") {
                        this.userList = res.data;
                    }
                });
            },
    // 查询自己的权限
    getRole() {
      console.log("我要过来判断权限");
      console.log(this.$store.state.user.roles.toString());
      // 判断是管理员  全都可以操作
      if (this.$store.state.user.roles.toString().indexOf("ROLE_ADMIN") != -1) {
        this.businessTypeChannel = "03";
        this.ownBusinessTypeChannel = "03";
        console.log("我是管理员");
      } else {
        // 说明不是管理员 那么需要判断他有哪些管理角色
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OTHER_NEW_MANAGE_CHANNEL_DEVELOP") != -1
        ) {
          // 说明是新车非直营管理
          this.businessTypeChannel = "01";
          console.log("我是非直营新车");
        }
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OTHER_OLD_MANAGE_CHANNEL_DEVELOP") != -1 
        ) {
          // 说明是二手车非直营管理
          if (this.businessTypeChannel == "01") {
            this.businessTypeChannel = "03";
            console.log("我是非直营新车二手车");
          } else {
            this.businessTypeChannel = "02";
            console.log("我是非直营二手车");
          }
        }
        // 再去判断直营的角色属性
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OWN_NEW_MANAGE_CHANNEL_DEVELOP") != -1 
        ) {
          //我是直营的新车属性
          this.ownBusinessTypeChannel = "01";
          console.log("我是直营新车");
        }
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OWN_OLD_MANAGE_CHANNEL_DEVELOP") != -1
        ) {
          if (this.ownBusinessTypeChannel == "01") {
            this.ownBusinessTypeChannel = "03";
            console.log("我是直营新车二手车");
          } else {
            this.ownBusinessTypeChannel = "02";
            console.log("我是二手车直营");
          }
        }
      }
    },
    // 获取部门树
    getParentList() {
      this.loading = true;
      let id = "0";
      initAppertainRegion(id).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent === "1") {
              e.loading = false;
              e.children = [];
              e.expand = true;
            }
          });
          this.areaData = res.data;
          console.log(this.areaData[0]);
          getUserByParentId(res.data[0].id).then(res => {
            if (res.code === "0000") {
              // 先把数据塞给上级
              res.data.forEach(function(e) {
                if (e.isParent === "1") {
                  e.loading = false;
                  e.children = [];
                }
              });
              this.areaData[0].children = res.data;
              // callback(res.data);
            }
          });
        }
      });
      this.cancelEdit();
    },

    search() {
      if (this.searchKey) {
        searchAppertainRegion({ title: this.searchKey }).then(res => {
          if (res.code === "0000") {
            this.areaData = res.data;
          }
        });
      } else {
        this.getParentList();
      }
    },

    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
    },

    areaLoadData(item, callback) {
      console.log(callback);
      console.log("发展1");
      getUserByParentId(item.id).then(res => {
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent === "1") {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.data);
        }
      });
      console.log(this.areaData);
    },
    changeSelect(v) {
      console.log("发展2");
      this.selectCount = v.length;
      this.selectList = v;
    },
    selectTree(v) {
      var obj = { abc: "ss", nn: 90 };
      var v1 = obj.abc; //
      console.log(v1);
      console.log("发展4");
      console.log(JSON.stringify(v));
      if (v.length > 0) {
        // 转换null为""
        var a = JSON.stringify(v[0]);
        let data = JSON.parse(a);
        this.searchForm.regionLevel = data.level; // 层级
        this.searchForm.regionId = data.id; // 选中的id
        this.searchForm.userId = data.userId; // 选中的用户id
        this.searchForm.lowerUserIds =data.lowerUserIds; //子类的集合
        console.log("选中选择！");
        console.log(this.searchForm.regionLevel);
        this.handleSearch();
      } else {
        console.log("取消选择！");
        this.searchForm.regionLevel = null; // 层级
        this.searchForm.regionId = null; // 选中的id
         this.searchForm.userId = null; // 选中的用户id
         this.searchForm.lowerUserIds =[];
        this.cancelEdit();
        this.handleReset();
      }
    },

    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getChannelList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getChannelList();
    },
    selectDateRange(v) {
      if (v) {
        this.searchForm.startDate = v[0];
        this.searchForm.endDate = v[1];
      }
    },
    // 多条件搜索渠道列表
    getChannelList() {
      this.loading = true;
      this.searchForm.channelCity =this.searchForm.channelAddress;
      getByDevelop(this.searchForm).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          this.data = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // 查询接口
    handleSearch() {
      // 查询合作商数据列表
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getChannelList();
    },
    // 重置
    handleReset() {
      if (this.isNewCarRole == "1" && this.isOldCarRole == "1") {
        this.searchForm.newCar = false;
        this.searchForm.oldCar = false;
      }

      this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.selectDate = null;
      this.searchForm.startDate = "";
      this.searchForm.endDate = "";
      this.selectAuthFegion = [];
      this.searchForm.authFegion = "";
      // 重新加载数据
      this.getChannelList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order === "normal") {
        this.searchForm.order = "";
      }
      this.getChannelList();
    },
    cancelChannel() {
      //关闭窗口
      this.channelModalVisible = false;
    },
    submitChannel() {
      this.$refs.channelForm.validate(valid => {
        if (valid) {
          let param = {
            //按钮是否隐藏：保存、提交、返回展示，黑名单隐藏
            bottonView: 0,
            //信息是否只读:1 非只读
            infoView: 1,
            //操作类型：0，新增
            operationType: 0,
            //渠道归属新增的时候通过选择传值
            channelType: this.channelForm.channelType,
            isNewCarRole: this.isNewCarRole,
            isOldCarRole: this.isOldCarRole
          };
          this.channelModalVisible = false;
          this.afs.newTab(
            this,
            "projects/afs-channel/pages/dealer-apply/dealer-online/dealerIndex",
            "信息录入",
            "ios-add",
            param,
            "channelOnline-add",
            [],
            true
          );
        }
      });
    },
    add() {
      if (this.isNewCarRole == "0" && this.isOldCarRole == "0") {
        //表示当前用户既没有新车权限，也没有二手车权限
        this.$Message.error(
          "当前用户既无新车权限也无二手车权限，请维护后并刷新！"
        );
        return;
      }
      //新增页面
      this.modalType = 0;
      this.modalTitle = "             ";
      this.$refs.channelForm.resetFields();
      this.channelModalVisible = true;
    },
    checkArea() {
      if (this.border == "0") {
        this.getAllRegionalManagerNew();
      } else if (this.border == "1") {
        this.getAllRegionalManagerOld();
      }
    },
     upBatch() {
      if (this.clickCount <= 0) {
        this.$Message.warning("您还未选择要更改的数据");
        return false;
      }
      // 先去取第一个集合中第一个类型
      if (this.clickList.length == 1) {
        if (this.clickList[0].businessType == "01,02") {
          this.border = "0";
          this.clickHide = null;
          this.getAllRegionalManagerNew();
          //我现在现在是新车和二手车
          console.log("我只有一个并且我是新车和二手车");
        } else if (this.clickList[0].businessType == "01") {
          this.border = "0";
          this.getAllRegionalManagerNew();
          // 说明我是新车
          this.clickHide = "disabled";
          console.log("我只有一个我只有新车");
        } else if (this.clickList[0].businessType == "02") {
          // 说明我是二手车
          this.border = "1";
          this.clickHide = "disabled";
          this.getAllRegionalManagerOld();
          console.log("我只有一个我只有二手车");
        } else {
          this.$Message.warning("选择数据有误,请刷新！");
          return;
        }
      } else {
        
        // 声明一个类型
        var c = "01,02";

        // 默认声明一个直营
        var ownAll=null;
        // 声明一个 非直营的
        var otherAll=null;
        // 说明选择数据是多条
        for (var i = 0; i < this.clickList.length; i++) {
          if(this.clickList[i].channelBelong=='01'){
            // 说明我是直营
            ownAll='03';
          }else{
            // 说明我是非直营
            otherAll='03';
          }
          if (this.clickList[i].businessType != "01,02") {
            if (c == "01,02") {
              // 当为00 的时候去赋值
              c = this.clickList[i].businessType;
            } else {
              if (c != this.clickList[i].businessType) {
                this.$Message.warning("选择业务类型相同的数据");
                return;
              }
            }
          }
          
        }

        // 走完之后看数据
        if (c == "01,02") {
          // 说明我是新车和二手车  我要赋值给新车
          this.border = "0";
          this.getAllRegionalManagerNew();
          this.clickHide = null;
          console.log("我有多个并且我是新车和二手车");
        } else if (c == "01") {
          // 说明只有新车
          this.border = "0";
          this.clickHide = "disabled";
          this.getAllRegionalManagerNew();
          console.log("我有多个并且我是新车");
        } else if (c == "02") {
          // 说明我是二手车
          this.border = "1";
          this.clickHide = "disabled";
          this.getAllRegionalManagerOld();
          console.log("我有多个并且我是二手车");
        } else {
          this.$Message.warning("数据有误,请刷新！");
          return;
        }
      }
      this.modal2 = true;
    },
    // 确认更改
    dels() {
      if (
        this.areaManager == null ||
        this.areaManager == "" ||
        this.areaManager == undefined
      ) {
        this.$Message.warning("请选择区域经理");
        return;
      }
      let ids = [];
      this.clickList.forEach(function(e) {
        ids += e.id + ",";
      });
      ids = ids.substring(0, ids.length - 1);
      var cc;
      if (this.border == "0") {
        cc = "01";
      } else if (this.border == "1") {
        cc = "02";
      }
      let obj = {
        ids: ids,
        border: cc,
        areaManager: this.areaManager
      };
      console.log("修改信息" + obj.ids);
      console.log(obj.border);
      console.log(this.areaManager);
      batchManager(obj).then(res => {
        if (res.code === "0000") {
          this.$Message.success("修改成功");
          this.clickList = [];
          this.clickCount = 0;
          this.areaManager = null;
          this.clearSelectAll();
          this.modal2 = false;
        }
      });
    },
    //新车区域经理
    getAllRegionalManagerNew() {
      //获取当前区域经理下面所有的业务人员
      getAllRegionalManager("ROLE_NEW_REG_MANAGER").then(res => {
        if (res.code === "0000") {
          this.regionalManager = res.data.data;
          this.userAreaManger = this.regionalManager;
        }
      });
    },
    //二手车区域经理
    getAllRegionalManagerOld() {
      //获取当前二手车区域经理下面所有的业务人员
      getAllRegionalManager("ROLE_OLD_REG_MANAGER").then(res => {
        if (res.code === "0000") {
          this.regionalManagerOld = res.data.data;
          this.userAreaManger = this.regionalManagerOld;
        }
      });
    },

    edit(v) {
      let param = {
        //按钮是否隐藏：保存、提交、返回展示，黑名单隐藏
        bottonView: 0,
        //信息是否只读:1 非只读
        infoView: 1,
        //操作类型：1，修改
        operationType: 1,
        //渠道id
        channelId: v.id,
        channelType: v.channelBelong,
        isNewCarRole: this.isNewCarRole,
        isOldCarRole: this.isOldCarRole,
        channelStatus: v.channelStatus,
        channelStatusOldCar: v.channelStatusOldCar
      };
      this.channelModalVisible = false;
      this.afs.newTab(
        this,
        "projects/afs-channel/pages/dealer-apply/dealer-online/dealerIndex",
        "信息修改",
        "ios-add",
        param,
        "channelOnline-edit" + v.id,
        [],
        true
      );
    },
    back() {
      this.parentGroup = true;
    },
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除 " + v.channelFullName + " ?",
        onOk: () => {
          this.operationLoading = true;
          deleteChannel(v.id).then(res => {
            this.operationLoading = false;
            if (res.code === "0000") {
              this.$Message.success("删除成功");
              this.getChannelList();
            }
          });
        }
      });
    },
    showChannelName(v) {
      var aa=0;
      var bb=0;
      if(this.businessTypeChannel=='01'||this.businessTypeChannel=='03'||this.ownBusinessTypeChannel=='01'||this.ownBusinessTypeChannel=='03'){
        aa=1;
      }
      if(this.businessTypeChannel=='02'||this.businessTypeChannel=='03'||this.ownBusinessTypeChannel=='02'||this.ownBusinessTypeChannel=='03'){
        bb=1;
      }
      let param = {
        //按钮是否隐藏：保存、提交、隐藏，返回、黑名单展示
        bottonView: 1,
        //信息是否只读:1 只读
        infoView: 0,
        //操作类型：1，查看
        operationType: 2,
        //渠道id
        channelId: v.id,
        
        isNewCarRole: aa,
        isOldCarRole: bb,
      };
      this.channelModalVisible = false;
      this.afs.newTab(
        this,
        "projects/afs-channel/pages/dealer-apply/dealer-online/dealerIndex",
        "信息查看",
        "ios-view",
        param,
        "channelOnline-view" + v.id,
        [],
        true
      );
    },
    dropDown() {
      if (this.drop) {
        this.dropDownContent = "更多";
        this.dropDownIcon = "ios-arrow-down";
      } else {
        this.dropDownContent = "收起";
        this.dropDownIcon = "ios-arrow-up";
      }
      this.drop = !this.drop;
    },
    // 这个是点击复选框触发的事件
    showSelect(e) {
      this.clickList = e;
      this.clickCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    loadData(item, callback) {
      item.loading = true;
      getAllAddressList(item.value).then(res => {
        item.loading = false;
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.value = e.id;
              e.label = e.title;
              e.loading = false;
              e.children = [];
            } else {
              e.value = e.id;
              e.label = e.title;
            }
          });
          item.children = res.data;
          callback();
        }
      });
    },
    handleChangeAuthFegion(value, selectedData) {
      // 获取最后一个值
      if (value && value.length > 0) {
        this.searchForm.authFegion = value[value.length - 1];
      } else {
        this.searchForm.authFegion = "";
      }
    },
    // 选中注册省市
    handleChannelAddress(value, selectedData){
                // 获取最后一个值
                console.log("////////",value);
                if (value && value.length > 0) {
                    this.searchForm.channelAddress = value[value.length - 1];
                } else {
                    this.searchForm.channelAddress = "";
                }
            },
    getMainAreaList() {
      console.log("这是干嘛的");
      getAllAddressList().then(res => {
        this.loading = false;
        if (res.code === "0000") {
          // 仅展开指定级数 默认一级
          let expandLevel = this.expandLevel;
          res.data.forEach(function(e) {
            if (expandLevel == "0") {
              if (e.addrLevel === "0") {
                e.expand = true;
                e.value = e.id;
              }
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (c.addrLevel === "1") {
                    c.expand = false;
                    c.value = e.id;
                  }
                });
              }
            } else {
              if (e.children && e.children.length > 0) {
                e.children.forEach(function(c) {
                  if (expandLevel == 1) {
                    if (c.addrLevel === "1") {
                      c.expand = false;
                      c.value = e.id;
                    }
                  }
                });
              }
            }
          });
          this.authFegionDate = res.data;
        }
      });
    },

    //新车合作商状态
    setChannelStatusTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      this.channelStatusList.forEach(column => {
        if (column.value === val) {
          dic = column;
        }
      });
      return dic.title;
    },
    //二手车合作商状态
    setChannelStatusOldCarTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      this.channelStatusOldCarList.forEach(column => {
        if (column.value === val) {
          dic = column;
        }
      });
      return dic.title;
    },

    //渠道归属
    setChannelBelongTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      this.channelBelongList.forEach(column => {
        if (column.value === val) {
          dic = column;
        }
      });
      return dic.title;
    },

    //评级：需区分新车评级，二手车评级
    setChannelGradeTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      let valTemp = val.split(",");
      if (valTemp.length > 1) {
        let title = "";
        for (let i in valTemp) {
          this.channelGradeList.forEach(column => {
            if (column.value === valTemp[i]) {
              dic = column;
              title = title + "   " + dic.title;
            }
          });
        }
        return title;
      } else {
        let dic = {};
        this.channelGradeList.forEach(column => {
          if (column.value === val) {
            dic = column;
          }
        });
        return dic.title;
      }
    },
    //业务类型处理
    setBusinessTypeTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      let valTemp = val.split(",");
      if (valTemp.length > 1) {
        let title = "";
        for (let i in valTemp) {
          this.businessTypeList.forEach(column => {
            if (column.value === valTemp[i]) {
              dic = column;
              title = title + "  " + dic.title;
            }
          });
        }
        return title;
      } else {
        let dic = {};
        this.businessTypeList.forEach(column => {
          if (column.value === val) {
            dic = column;
          }
        });
        return dic.title;
      }
    },

    //客户经理
    setCustomerManagerTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      let valTemp = val.split(",");
      if (valTemp.length > 1) {
        let title = new Set();
        for (let i in valTemp) {
          this.customerManagerList.forEach(column => {
            if (column.userName === valTemp[i]) {
              dic = column;
              // title =title+"   "+dic.userRealName;
              title.add(dic.userRealName);
            }
          });
        }
        return [...title].join(" ");
      } else {
        let dic = {};
        this.customerManagerList.forEach(column => {
          if (column.userName === val) {
            dic = column;
          }
        });
        return dic.userRealName;
      }
    },

    //优质等级
    setQualityGradeTitle(val) {
      if (val == null || val == "" || val == undefined) {
        return;
      }
      let dic = {};
      let valTemp = val.split(",");
      if (valTemp.length > 1) {
        let title = "";
        for (let i in valTemp) {
          this.qualityGradeList.forEach(column => {
            if (column.value === valTemp[i]) {
              dic = column;
              title = title + "   " + dic.title;
            }
          });
        }
        return title;
      } else {
        let dic = {};
        this.qualityGradeList.forEach(column => {
          if (column.value === val) {
            dic = column;
          }
        });
        return dic.title;
      }
    },

    initLabelType() {
      let channelStatusDic = "channelStatus";
      getDictDataByType(channelStatusDic).then(res => {
        if (res.code === "0000") {
          this.channelStatusList = res.data;
        }
      });

      let channelBelongDic = "channelBelong";
      getDictDataByType(channelBelongDic).then(res => {
        if (res.code === "0000") {
          this.channelBelongList = res.data;
        }
      });

      let channelStatusOldDic = "channelStatus";
      getDictDataByType(channelStatusOldDic).then(res => {
        if (res.code === "0000") {
          this.channelStatusOldCarList = res.data;
        }
      });

      let channelGradeDic = "channelGrade";
      getDictDataByType(channelGradeDic).then(res => {
        if (res.code === "0000") {
          this.channelGradeList = res.data;
        }
      });

      let businessTypeDic = "businessType";
      getDictDataByType(businessTypeDic).then(res => {
        if (res.code === "0000") {
          this.businessTypeList = res.data;
        }
      });

      // let customerManagerDic="customerManager";
      // getDictDataByType(customerManagerDic).then(res =>{
      //     if (res.code === "0000"){
      //         this.customerManagerList = res.data;
      //     }
      // });

      let qualityGradeDic = "qualityGrade";
      getDictDataByType(qualityGradeDic).then(res => {
        if (res.code === "0000") {
          this.qualityGradeList = res.data;
        }
      });
    },

    // 查询数据字典
    initDataDic() {
      this.channelBelongType();
      this.channelStatusType();
      this.qualityGradeType();
    },
    //渠道归属数据字典
    channelBelongType() {
      let param = {
        type: "channelBelong"
      };
      getDictDataByType(param.type).then(res => {
        if (res.code === "0000") {
          this.channelBelongList = res.data;
        }
      });
    },
    //渠道状态字典
    channelStatusType() {
      let param = {
        type: "channelStatus"
      };
      getDictDataByType(param.type).then(res => {
        if (res.code === "0000") {
          this.channelStatusList = res.data;
        }
      });
    },

    //优质等级
    qualityGradeType() {
      let param = {
        type: "qualityGrade"
      };
      getDictDataByType(param.type).then(res => {
        if (res.code === "0000") {
          this.qualityGradeList = res.data;
        }
      });
    },
    getAllRegionalManager() {
      //获取当前区域经理下面所有的业务人员
      let array = ["ROLE_NEW_REG_MANAGER", "ROLE_OLD_REG_MANAGER"];
      let customerManagerList = deepClone(this.customerManagerList);
      array.forEach(item => {
        getAllRegionalManager(item).then(res => {
          if (res.code === "0000") {
            customerManagerList.push(...res.data.data);
            this.customerManagerList = customerManagerList;
          }
        });
      });
    },
    //
    //反向解析省市地址
            getProvinceData() {
                let param = {level:"1",upperCode: "1"};
                getLocation(param).then(res => {
                    if(res.code === "0000"){
                        this.province=res.data;
                    }
                });
            },
            getCityData() {
                let param = {level:2,upperCode:''};
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        this.city=res.data;
                    }
                });
            },

            //翻译省市
            getDetailAddress(registeredProvince,registeredCity,registeredAddress){
              console.log(registeredProvince+"----"+registeredCity+"-------"+registeredAddress)
                if(registeredProvince!="" && registeredCity!="" && registeredAddress !=""){
                    let province="";
                    let city="";
                    for(let i=0;i<this.province.length;i++){
                        if(this.province[i].value==registeredProvince){
                            province=this.province[i].label;
                        }
                    };
                    for(let i=0;i<this.city.length;i++){
                        if(this.city[i].value==registeredCity){
                            city=this.city[i].label;
                        }
                    };
                    return province+city+registeredAddress;
                }else{
                    return '';
                }
            },
            //调用省市的方法
            getLocationData() {
                let param = ""
                param = {
                    level: '1',
                    upperCode: '1'
                };
                getLocation(param).then((res) => {
                    if (res.code == "0000") {
                        res.data.forEach(item => {
                            // 表明是否是父节点
                            if (item.isParent) {
                                getLocation({upperCode: item.value}).then(res => {
                                    if (res.code === "0000") {
                                        item.children = res.data;
                                        this.location.push(item);
                                    }
                                })
                            }
                        })
                    }
                    // this.location.push(...res.data);
                })
            },
  },
  created() {
    this.initDataDic();
  },
  mounted() {
    this.init();
  }
};
</script>